// pages/beauty/beauty.js
Page({
  data: {
    imagePath: '',
    result: null,
    loading: false,
    showResult: false
  },

  // 选择图片
  chooseImage() {
    const that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        that.setData({
          imagePath: tempFilePath,
          showResult: false,
          result: null
        });
      },
      fail(err) {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 拍照
  takePhoto() {
    const that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        that.setData({
          imagePath: tempFilePath,
          showResult: false,
          result: null
        });
      },
      fail(err) {
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
    });
  },

  // 分析颜值
  async analyzeBeauty() {
    if (!this.data.imagePath) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });
    const apiUrl = getApp().globalData.api_url + 'api/beauty/analyze';

    try {
      // 上传图片并分析
      const uploadTask = wx.uploadFile({
        url: apiUrl,
        filePath: this.data.imagePath,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.success) {
            this.setData({
              result: data.data,
              showResult: true,
              loading: false
            });
          } else {
            throw new Error(data.message || '分析失败');
          }
        },
        fail: (err) => {
          this.setData({ loading: false });
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      });

    } catch (error) {
      this.setData({ loading: false });
      wx.showToast({
        title: error.message || '分析失败',
        icon: 'none'
      });
    }
  },

  // 重新分析
  resetAnalysis() {
    this.setData({
      imagePath: '',
      result: null,
      showResult: false,
      loading: false
    });
  },

  // 保存结果图片
  saveResult() {
    if (this.data.imagePath) {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.imagePath,
        success() {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
        },
        fail() {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
    }
  },

  onLoad(options) {
    // 页面加载时的逻辑
  },

  onShareAppMessage() {
    return {
      title: 'AI颜值检测',
      path: '/pages/beauty/beauty'
    };
  }
});